#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <iostream>
#include <thread>
using namespace std;

class client{
    private:
         int server_port; //服务器端口
         string server_ip;//服务器ip
         int sock;//与服务器建立连接的套接字描述符；
    public:
         client(int port,string ip);
         ~client();
         void run();//启动客户端服务；
         static void SendMsg(int conn);//发送线程
         static void RecvMsg(int conn);//接收线程

};
client::client(int port,string ip):server_port(port),server_ip(ip){}
client::~client(){
    close(sock);
}

void client::run(){
   //1.定义sockfd
    sock = socket(AF_INET,SOCK_STREAM,0);

    //定义 sockaddr_in
    struct sockaddr_in cliddr;
    memset(&cliddr,0,sizeof(cliddr));
    cliddr.sin_family=AF_INET;//TCP/IP 协议族
    cliddr.sin_port=htons(server_port); //服务器端口；
    cliddr.sin_addr.s_addr=inet_addr(server_ip.c_str());//服务器ip

    //2.连接服务器，成功返回0，错误返回-1；
    if(connect(sock,(struct sockaddr*)&cliddr,sizeof(cliddr))<0){
        perror("connect");
        exit(1);
    }
    cout<<"连接服务器成功！\n";
    //3.创建发送线程和接收线程
    thread send_t(SendMsg,sock),recv_t(RecvMsg,sock);
    send_t.join();
    cout<<"发送线程已结束\n";
    recv_t.join();
    cout<<"接收线程已结束\n";
    return;
}
void client::SendMsg(int conn){
    char sendbuf[100];
    while(1){
        memset(sendbuf,0,sizeof(sendbuf));
        cin>>sendbuf;
        int ret=send(conn,sendbuf,strlen(sendbuf),0);//发送
        //输入exit或对端关闭时结束
        if(strcmp(sendbuf,"exit")==0||ret<=0)
          break;
    }
}
void client::RecvMsg(int conn)
{
    //接收缓冲区
    char buffer[1000];
    //不断接收数据
    while(1){
        memset(buffer,0,sizeof(buffer));
        int len =recv(conn,buffer,sizeof(buffer),0);
        //recv返回值小于等于0，退出
        if(len<=0)
            break;
        cout<<"收到服务器发来的信息:"<<buffer<<endl;
    }
}
int main()
{
    
    client clnt(8023,"127.0.0.1");
    clnt.run();

}